/*=============================================================================
#    The element-comm is a tentative program used to test our ideas.           
#                       Copyright (C)  bgao                                    
#
#     This program is free software; you can redistribute it and/or            
#      modify it under the terms of the GNU General Public License             
#     as published by the Free Software Foundation; either version 2           
#         of the License, or (at your option) any later version.               
#
#     This program is distributed in the hope that it will be useful,          
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            
#             GNU General Public License for more details.                    
#
#    You should have received a copy of the GNU General Public License        
#     along with this program; if not, write to the Free Software             
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,             
#                       MA  02110-1301, USA.                                  
#==============================================================================
# $Id: mac_retry.c 348 2010-11-29 09:01:16Z bgao $ 
#
# $Author: bgao $ 
#
# $Revision: 348 $ 
#
# $Date: 2010-11-29 17:01:16 +0800 (星期一, 29 十一月 2010) $ 
#
# Description: 
#
=============================================================================*/
/*! @file mac_retry.c
 *  @brief This file implements the MAC acknowledgement mechanism.
 */
#include "mac.h"
#include <string.h>
#if 0
#include "mac_retry.h"
#include "timer.h"
#endif

/*! the maximum number of buffer element in this buffer. */
#define MAC_RETRY_BUF_COUNT 10

/*! the instance of the retry */
LIST(mac_retry);
MEM(mr_free_list);

/*! instance of the retry pool */
static mac_retry_t mac_retry_pool[MAC_RETRY_BUF_COUNT];

/*! the retry timer, used to periodically check if there are any
 *  item in this retry pool timeouts.
 */
static mtimer_t retry_timer;
static void mac_retry_timeout(int8 signum);

/*! initialize the mac retry queue.
 *  @return MAC_ERR(-1) if the list or the mem sub module malfunction
 *          else return MAC_OK(1).
 */
int8 mac_retry_init(void)
{
    int r, t;
    pool_t p;

    p.ptr = mac_retry_pool;
    p.num = MAC_RETRY_BUF_COUNT;
    p.size = sizeof(mac_retry_t);

    memset(mac_retry_pool, 0, sizeof(mac_retry_pool));
    r = list_init(mac_retry);
    t = mem_init(mr_free_list, &p);

    /* start timer */
    timer_init(&retry_timer, mac_retry_timeout);
    /* use the timer which has a bigger resolusion, then the time out timer should be adjusted */
    /* TODO select a suitable timeout number when the tick set */ 
    timer_start(&retry_timer, 1);

    if (r == MAC_ERR || t == MAC_ERR)
        return MAC_ERR;
    else
        return MAC_OK;
}

/*! allocate a entry from the mac retry queue.
 *  @return pointer to the allocated entry, return NULL if no free entry.
 */
mac_retry_t *mac_retry_alloc(void)
{
    mac_retry_t *m;
    uint32 r;

    m = mem_alloc(mr_free_list);
    if (m == NULL) {
        return NULL;
    }
    m->retries = mac_get_max_frame_retries();
    m->timeout = mac_get_ack_wait_duration();

    r = list_add_head(mac_retry, m);
    if (r == MAC_ERR) {
        return NULL;
    }

    m = list_get_head(mac_retry);

    return m;
}

/*! free the allocated entry from mac retry queue.
 *  @param dsn the data sequence number of the entry to be freed.
 *  @return return MAC_ERR(-1) if no such entry exists else return MAC_OK(0).
 */
int8 mac_retry_free(uint8 dsn)
{
    mac_retry_t *m = list_get_head(mac_retry);

    for (; m != NULL; m = m->next) {
        if (m->dsn == dsn) {
            break;
        }
    }

    if (m == NULL) {
        return MAC_ERR;
    } else {
        list_del(mac_retry, m);
        return mem_free(mr_free_list, m);
    }
}

/*! find the entry whose dsn is equal to dsn.
 *  @param dsn the data senquence number of the entry being akced.
 *  @return pointer to the entry whose dsn is equal to dsn.
 */
mac_retry_t *mac_retry_find(uint8 dsn)
{
    mac_retry_t *m = list_get_head(mac_retry);

    if (m == NULL) {
        return NULL;
    }

    for (; m != NULL; m = m->next) {
        if (m->dsn == dsn) {
            break;
        }
    }

    if (m == NULL) {
        return NULL;
    } else {
        return m;
    }
}

/*! the expiry function
 *  the status should be reported to the upper layer
 */
static void mac_retry_timeout(int8 signum)
{
    /* check if there are indir items are time out */
    mac_retry_t *r = list_get_head(mac_retry);
    mac_indir_t *i;

    if (r == NULL) {
        timer_start(&retry_timer, 1);
        return;
    }

    for (; r != NULL; r = r->next) {
        if (r->timeout != 0) {
            r->timeout--;
        }
        if (r->timeout == 0) {
            /* if tx is faild and the tx was indirect, the device shall not retx the frame */
            i  = mac_indir_find_by_dsn(r->dsn);
            if (i != NULL) {
                list_del(mac_retry, r);
                mem_free(mr_free_list, r);
                continue;
            }

            /* tx was direct */
            /* retx up to retries+1 times */
            if (r->retries <= 0) {
                list_del(mac_retry, r);
                mem_free(mr_free_list, r);
            } else {
                /* retx */
                bool en_retry = true;
                mac_csmaca_tx(r->buf, r->dsn, en_retry);
                r->retries--;
                r->timeout = mac_get_ack_wait_duration();
            }
        }
    }

    /* TODO select a suitable timeout number when the tick is set */
    timer_start(&retry_timer, 1);
}
